<template>

  <div>
    <!--面包屑导航栏-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!--用户列表主体，将信息聚合在卡片容器中展示，包含标题、内容和操作-->
    <el-card>
      <el-row :gutter="25">
        <el-col :span="10">
          <el-input placeholder="请输入搜索的用户信息" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>

        <el-col :span="5">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--stripe实现隔行变色-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="状态" prop="state">
          <!--作用域插槽-->
          <template slot-scope="scope">
            <!--scope.row获取每一行的数据 也就是说每一行每一个人的信息-->
            <el-switch v-model="scope.row.state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--修改-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!--删除-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <!--权限-->
            <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--实现分页-->
      <div class="page-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum"
            :page-sizes="[1, 5, 10, 50]"
            :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"> <!--我们已经在后台传进来的数据中绑定好了total-->
        </el-pagination>
      </div>
    </el-card>

    <!--添加用户的对话框-->
    <el-dialog title="添加新用户" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"  prefix-icon="el-icon-user-solid"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" prefix-icon="el-icon-connection"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </span>

    </el-dialog>


    <!--修改用户对话框-->
    <el-dialog title="修改新用户" :visible.sync="editDialogVisible" width="40%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">确定</el-button>
      </span>

    </el-dialog>

  </div>

</template>

<script>
export default {
  data(){
    return{
      // 查询信息实体
      queryInfo:{
        query:"",  // 用户输入的查询信息
        pageNum:1, // 当前页
        pageSize:10, // 每页最大数（后面会实现动态调整
      },
      userList:[],  // 用户列表
      total: 0,  // 总记录数
      addDialogVisible:false,   // 添加用户的对话框默认不现实
      addForm:{
        username:'',   // 用户名
        password:'', // 密码
        email:'',  // 邮箱
      },
      // 修改用户信息
      editForm:{

      },
      // 显示和隐藏修改用户栏
      editDialogVisible:false,


      // 添加用户表单验证结果
      addFormRules:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
        ],
        // 设置密码的校验规则：1.失去焦点时如果没有输入密码提示  2.密码的长度为6~10个字符
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },
      // 修改表单验证
      editFormRules:{
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods:{
    async getUserList(){
      const {data:res} = await this.$http.get("alluser",{params:this.queryInfo}) // 通过get携带参数的方式将请求alluser
      this.userList = res.data;  // 后台传过来的data给userList进行绑定
      this.total = res.numbers;  // 后台传过来的num给total进行绑定
    },
    handleSizeChange(newSize){
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage){
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },
    async changeState(userinfo){
      const {data:res} = await this.$http.put(`updateState?id=${userinfo.id}&state=${userinfo.state}`);
      if (res === "error"){
        userinfo.id = !userinfo.id;
        this.$message.error("操作失败");
      }else{
        this.$message.success("操作成功")
      }
    },
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    addUser(){
      this.$refs.addFormRef.validate(async valid=>{
          if(!valid) return;
          const {data:res} = await this.$http.post("adduser",this.addForm);
          if (res!=="success"){
            return this.$message.error("添加失败！")
          }else{
            const h = this.$createElement;
            this.$notify({
              title: '添加成功',
              message: h('i', { style: 'color: teal'}, this.addForm.username+'已经入库啦')
            });
            this.addDialogVisible = false;
            await this.getUserList();
          }
      })
    },
    async deleteUser(id){
      const confirmResult = await this.$confirm('将删除该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== "confirm")return
      const {data:res} = await this.$http.delete("deleteuser?id="+id);
      if (res!=="success"){
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      await this.getUserList();
    },
    async showEditDialog(id){
      const {data:res} = await this.$http.get("updateUser?id="+id);
      this.editForm = res;
      this.editDialogVisible = true;
    },
    // 关闭窗口
    editDialogClosed(){
      this.$refs.editFormRef.resetFields(); // 重置信息
    },
    // 确认修改
    editUserInfo(){
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const {data:res} = await this.$http.put("editUser",this.editForm);
        if (res !== "success") return this.$message.error("操作失败");
        this.$message.success("操作成功");
        this.editDialogVisible = false;
        await this.getUserList();
      })
    }

  }
}
</script>

<style scoped>

.el-breadcrumb{
  margin-bottom: 15px;
  font-size: 18px;
}
.page-container{
  margin-top: 10px;
}

</style>
